package ge.unihack.instantdj.utils;

import ge.unihack.instantdj.R;
import ge.unihack.instantdj.protocol.common.LayerInfo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

public class LayerListAdapter extends BaseAdapter{

	private List<LayerInfo> mItems;
	private Activity mActivity;
	
	public LayerListAdapter(Context con){
		mActivity = ((Activity)con);
		mItems = new ArrayList<LayerInfo>();
	}
	
	@Override
	public int getCount() {
		return mItems.size();
	}

	public void addItem(LayerInfo item){
		mItems.add(item);
		notifyDataSetChanged();
	}
	
	public void removeItem(LayerInfo item){
		mItems.remove(item);
		notifyDataSetChanged();
	}
	
	public void removeItem(int itemPosition){
		mItems.remove(itemPosition);
		notifyDataSetChanged();
	}
	
	@Override
	public LayerInfo getItem(int arg0) {
		return mItems.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return mItems.get(arg0).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		Log.i(LayerListAdapter.class.getSimpleName(), "getView" + position);
		if(convertView == null){
			convertView  = mActivity.getLayoutInflater().inflate(R.layout.layout_layer_item, null);
		}
		
		Button btnChange = (Button) convertView.findViewById(R.id.btnChangeSound);
		ImageButton ibPlayPause = (ImageButton) convertView.findViewById(R.id.ibPlayPause);
		
		final LayerInfo currentItem = mItems.get(position);
		
		int soundIconId = mActivity.getResources().getIdentifier(currentItem.getName(), "drawable", "ge.unihack.instantdj");
		Drawable soundIcon = mActivity.getResources().getDrawable(R.raw.drum_1);
		btnChange.setCompoundDrawables(soundIcon, null, null, null);
		btnChange.setText(currentItem.getName());
		
		btnChange.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
			}
		});
		
		ibPlayPause.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				ImageView iv = (ImageView)view;
				if(iv.getTag().equals("0")){
					iv.setTag("1");
					Drawable pauseDrawable = mActivity.getResources().getDrawable(R.drawable.pause);
					iv.setImageDrawable(pauseDrawable);
					try {
						PlayerDvijenia.play(mActivity, 4, currentItem.getName());
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
				}else{
					iv.setTag("0");
					Drawable playDrawable = mActivity.getResources().getDrawable(R.drawable.play);
					iv.setImageDrawable(playDrawable);
					PlayerDvijenia.pause(mActivity);
				}
			}
		});
		
		return convertView;
	}

}
